package com.fs.sys.service;

import com.fs.common.bean.UserContext;
import com.fs.common.bean.UserContextHolder;
import com.fs.common.exception.AppException;
import com.fs.common.exception.UnauthorizedException;
import com.fs.sys.bean.dto.TenantDTO;
import com.fs.sys.bean.dto.TenantUserDTO;
import com.fs.sys.bean.dto.UserDTO;
import com.fs.common.ErrorCodes;
import com.fs.sys.entityservice.TenantEntityService;
import com.fs.sys.entityservice.TenantUserEntityService;
import com.fs.sys.entityservice.UserEntityService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 租户用户服务
 *
 * @author LiuQi 2025/6/14-17:40
 * @version V1.0
 **/
@Service
public class TenantUserService {
    @Autowired
    private TenantUserEntityService service;

    @Autowired
    private UserEntityService userEntityService;

    @Autowired
    private TenantEntityService tenantEntityService;

    @Autowired
    private LoginService loginService;

    /**
     * 获取用户租户id列表
     * @param userId 用户id
     * @return 租户所属租户id列表
     */
    public List<String> userTenantIds(String userId) {
        List<TenantUserDTO> tenantUserList = service.findByUser(userId);
        if (CollectionUtils.isEmpty(tenantUserList)) {
            return new ArrayList<>(0);
        }

        return tenantUserList.stream().map(TenantUserDTO::getTenantId).toList();
    }

    /**
     * 查找用户租户列表
     * @return 租户列表
     */
    public List<TenantDTO> userTenants(String userId) {
        List<String> tenantIds = this.userTenantIds(userId);
        if (CollectionUtils.isEmpty(tenantIds)) {
            return new ArrayList<>(16);
        }
        return tenantEntityService.findByIds(tenantIds);
    }

    /**
     * 切换用户当前租户
     * @param tenantId 切换后的租户
     * @param userId 用户id
     */
    public void switchTenant(String tenantId, String userId) {
        // 先判断租户是否存在
        List<TenantUserDTO> tenantUserList = service.findByUser(userId);
        boolean find = false;
        for (TenantUserDTO tenantUserDTO : tenantUserList) {
            if (tenantId.equals(tenantUserDTO.getTenantId())) {
                find = true;
                break;
            }
        }
        if (!find) {
            throw AppException.of(ErrorCodes.BASE_USER_NOT_IN_TENANT);
        }

        // 更新用户表当前租户信息
        UserDTO updateExp = new UserDTO();
        updateExp.setId(userId);
        updateExp.setCurrentTenantId(tenantId);
        userEntityService.update(updateExp);

        // 重新生成token并设置cookie
        UserContext userContext = UserContextHolder.get().orElseThrow(UnauthorizedException::new);
        userContext.setTenantId(tenantId);
        loginService.setCookieToken(userContext);
    }

    /**
     * 从租户中移除用户
     * @param userIds 用户id列表
     */
    public void deleteByUser(String tenantId, List<String> userIds) {
        service.deleteBuilder()
                .eq("tenant_id", tenantId)
                .in("user_id", userIds)
                .delete();
    }
}
